package com.api.sw.duban.action;

import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.api.sw.duban.model.Assigned;
import com.api.sw.duban.model.FkTimejl;
import com.api.sw.duban.service.AssignedBaseService;
import com.api.sw.duban.service.FkTimeBaseService;
import com.api.sw.duban.util.*;
import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.*;
import com.cloudstore.eccom.result.WeaResultMsg;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import weaver.conn.RecordSet;
import weaver.general.PageIdConst;
import weaver.general.Util;
import weaver.hrm.User;

import java.text.SimpleDateFormat;
import java.util.*;

/*
    决策督查  特批相关的 action
 */
public class DubanTpAction {
    private final static LogTool log = new LogTool("/log/duban/",false);
    public DubanTpAction(){

    };
    /*
        汇出Word
     */
    public XWPFDocument ExprotWord(Map<String,Object> params){
        XWPFDocument document=null;
        try {
            String tzid = (String) Util.null2String(params.get("tzid"));//通知ID
            if("".equals(tzid)){
                return document;
            }
            //获取规则字段
            List<String> custTitle=DubUtil.getCustFeild(tzid);
            if(custTitle==null||custTitle.size()<=0){
                return document;
            }
            //获取数据

            int col=custTitle.size();
            custTitle.add("落实情况");
            custTitle.add("牵头单位");
            List<List<String>> dataList=new ArrayList<List<String>>();
            dataList.add(custTitle);//设置第一行
            RecordSet re=new RecordSet();
            dubanTran dubanTran=new dubanTran();
            //升序
            String bt="";
            String sql=" select a.* ,b.bt bbt from uf_jcdcrw a,uf_jcdctz b  where a.ssdctz=b.id and  a.sfsrw='0' and a.ssdctz='"+tzid+"' order by a.sssj ";
            log.writeLog("ExprotWord---"+sql);
            re.execute(sql);
            List<String> datademo=null;
            while(re.next() ){
                datademo=new ArrayList<String>();
                bt=Util.null2String(re.getString("bbt"));//通知标题
                String rwid=Util.null2String(re.getString("id"));//任务ID
                String gzrw=Util.null2String(re.getString("gzrw"));//工作任务
                String qtdw=dubanTran.getSwDpartmentnameByid(Util.null2String(re.getString("qtdw")));//签收单位名称
                String lsqk=getNewJlbyRwid(rwid);//最新落实情况
                // 设置遍历所有的主任务
                setListByRw(datademo,rwid,col);
                datademo.add(lsqk);
                datademo.add(qtdw);
                dataList.add(datademo);
            }
            if(dataList.size()>0){//设置 Word数据
                int w=WordExport.DOCW;
                int h=WordExport.DOCH;
                WordExport wordExport=new WordExport(w,h);
                //3700,3700  落实情况  牵头单位
                List<String> title11 = new ArrayList<String>();
                title11.add(bt);
                int[] colWidths=getCellW(col,w,(col)+2);
                wordExport.makeWord(title11,dataList, new ArrayList<String>(), "",colWidths);
                document=wordExport.getDocument();
            }

        }catch(Exception e){

        }
        return document;
    }
    /*
        汇出计划Word
     */
    public XWPFDocument ExprotPlayWord(Map<String,Object> params){
        XWPFDocument document=null;
        try {
            String tzid = (String) Util.null2String(params.get("tzid"));//通知ID
            if("".equals(tzid)){
                return document;
            }
            //获取规则字段
            List<String> custTitle=DubUtil.getCustFeild(tzid);
            log.writeLog(custTitle.toString());
            if(custTitle==null||custTitle.size()<=0){
                return document;
            }
            //获取数据

            int col=custTitle.size();
            int wihcol=col;

            List<List<String>> dataList=new ArrayList<List<String>>();
            dataList.add(custTitle);//设置第一行
            RecordSet re=new RecordSet();
            dubanTran dubanTran=new dubanTran();
            //升序
            int listLen=0;
            String newjhlx="";
            String bt="";
            //获取最新的计划反馈 ,c.qtdw
            String sql=" select a.* from (select * from (select a1.*,row_number() over(partition by fkrwid order by id desc) datanum from uf_jcdcjdjh a1 where isnull(shqk,-1) in(0,1,-1) and jcdctz='"+tzid+"' ) where datanum=1) a,uf_jcdctz b,uf_jcrwfk c where a.jcdctz=b.id and a.fkrwid=c.id and b.id="+tzid;
            log.writeLog("ExprotPlayWord---"+sql);
            re.execute(sql);
            List<String> datademo=null;
            while(re.next() ){
                datademo=new ArrayList<String>();
                String jhlx=Util.null2String(re.getString("jhlx"));//计划类型
                if(listLen==0){
                    listLen=1;
                    if("0".equals(jhlx)){//季度
                        newjhlx=jhlx;
                        custTitle.add("第一季度");
                        custTitle.add("第二季度");
                        custTitle.add("第三季度");
                        custTitle.add("第四季度");
                        wihcol=wihcol+5;
                        custTitle.add("牵头单位");
                    }else if("1".equals(jhlx)){
                        newjhlx=jhlx;
                        custTitle.add("上半年");
                        custTitle.add("下半年");
                        wihcol=wihcol+3;
                        custTitle.add("牵头单位");
                    }else{
                        break;
                    }
                }
                bt="督查任务责任分工一览表";//Util.null2String(re.getString("bt"));//通知标题
                String rwid=Util.null2String(re.getString("jcdcrw"));//任务ID
                //String gzrw=Util.null2String(re.getString("gzrw"));//工作任务
                String qtdw=dubanTran.getSwDpartmentnameByid(Util.null2String(re.getString("qtdw")));//签收单位名称
                String lsqk=getNewJlbyRwid(rwid);//最新落实情况
                // 设置遍历所有的主任务
                setListByRw(datademo,rwid,col);

                String dyjd=Util.null2String(re.getString("dyjd"));//第一季度
                String dejd=Util.null2String(re.getString("dejd"));//第二季度
                String dsjd=Util.null2String(re.getString("dsjd"));//第三季度
                String dsijd=Util.null2String(re.getString("dsijd"));//第四季度
                String nz=Util.null2String(re.getString("nz"));//上
                String nd=Util.null2String(re.getString("nd"));//下
                if("0".equals(newjhlx)){
                    datademo.add(dyjd);
                    datademo.add(dejd);
                    datademo.add(dsjd);
                    datademo.add(dsijd);
                }else if("1".equals(newjhlx)){
                    datademo.add(nz);
                    datademo.add(nd);
                }else{
                    break;
                }


                //datademo.add(lsqk);
                datademo.add(qtdw);
                dataList.add(datademo);
            }
            log.writeLog("end set data");
            log.writeLog(dataList.toString());
            if(dataList.size()>0){//设置 Word数据
                int w=(WordExport.DOCW-3000);
                int h=WordExport.DOCH;
                WordExport wordExport=new WordExport(w,h);
                //3700,3700  落实情况  牵头单位
                List<String> title11 = new ArrayList<String>();
                title11.add(bt);
                log.writeLog(wihcol);
                int[] colWidths=getCellW(wihcol,w,wihcol);
                log.writeLog(colWidths);
                wordExport.makeWord(title11,dataList, new ArrayList<String>(), "",colWidths);
                document=wordExport.getDocument();
            }

        }catch(Exception e){

        }
        return document;
    }
    /*
       汇出计划Word + 落实请款
    */
    public XWPFDocument ExprotPlayWordls(Map<String,Object> params){
        XWPFDocument document=null;
        try {
            String tzid = (String) Util.null2String(params.get("tzid"));//通知ID
            if("".equals(tzid)){
                return document;
            }
            //获取规则字段
            List<String> custTitle=DubUtil.getCustFeild(tzid);
            List<String> custTitle2=DubUtil.getCustFeild(tzid);
            log.writeLog(custTitle.toString());
            if(custTitle==null||custTitle.size()<=0){
                return document;
            }
            //获取数据

            int col=custTitle.size();
            int wihcol=col;

            List<List<String>> dataList=new ArrayList<List<String>>();
            dataList.add(custTitle);//设置第一行
            dataList.add(custTitle2);//设置第一行
            RecordSet re=new RecordSet();
            dubanTran dubanTran=new dubanTran();
            //升序
            int listLen=0;
            String newjhlx="";
            String bt="";
            //获取最新的计划反馈 ,c.qtdw
            String sql=" select a.* from (select * from (select a1.*,row_number() over(partition by fkrwid order by id desc) datanum from uf_jcdcjdjh a1 where isnull(shqk,-1) in(0,1,-1) and jcdctz='"+tzid+"' ) where datanum=1) a,uf_jcdctz b ,uf_jcrwfk c where a.jcdctz=b.id and a.fkrwid=c.id  and b.id="+tzid;
            log.writeLog("ExprotPlayWord---"+sql);
            re.execute(sql);
            List<String> datademo=null;
            String jhlx="";
            while(re.next() ){
                datademo=new ArrayList<String>();
                jhlx=Util.null2String(re.getString("jhlx"));//计划类型
                if(listLen==0){
                    listLen=1;
                    if("0".equals(jhlx)){//季度
                        newjhlx=jhlx;
                        custTitle.add("工作计划");
                        custTitle2.add("第一季度");
                        custTitle.add("工作计划");
                        custTitle2.add("第二季度");
                        custTitle.add("工作计划");
                        custTitle2.add("第三季度");
                        custTitle.add("工作计划");
                        custTitle2.add("第四季度");
                        wihcol=wihcol+6;
                        custTitle.add("落实情况");
                        custTitle2.add("落实情况");
                        custTitle.add("牵头单位");
                        custTitle2.add("牵头单位");
                    }else if("1".equals(jhlx)){
                        newjhlx=jhlx;
                        custTitle.add("工作计划");
                        custTitle2.add("上半年");
                        custTitle.add("工作计划");
                        custTitle2.add("下半年");
                        wihcol=wihcol+4;
                        custTitle.add("落实情况");
                        custTitle2.add("落实情况");
                        custTitle.add("牵头单位");
                        custTitle2.add("牵头单位");
                    }else{
                        break;
                    }
                }
                bt="督查任务工作计划与落实情况汇总表";//Util.null2String(re.getString("bt"));//通知标题
                String rwid=Util.null2String(re.getString("jcdcrw"));//任务ID
                //String gzrw=Util.null2String(re.getString("gzrw"));//工作任务
                String qtdw=dubanTran.getSwDpartmentnameByid(Util.null2String(re.getString("qtdw")));//签收单位名称
                String lsqk=getNewJlbyRwid(rwid);//最新落实情况
                // 设置遍历所有的主任务
                setListByRw(datademo,rwid,col);

                String dyjd=Util.null2String(re.getString("dyjd"));//第一季度
                String dejd=Util.null2String(re.getString("dejd"));//第二季度
                String dsjd=Util.null2String(re.getString("dsjd"));//第三季度
                String dsijd=Util.null2String(re.getString("dsijd"));//第四季度
                String nz=Util.null2String(re.getString("nz"));//上
                String nd=Util.null2String(re.getString("nd"));//下
                if("0".equals(newjhlx)){
                    datademo.add(dyjd);
                    datademo.add(dejd);
                    datademo.add(dsjd);
                    datademo.add(dsijd);
                }else if("1".equals(newjhlx)){
                    datademo.add(nz);
                    datademo.add(nd);
                }else{
                    break;
                }


                //datademo.add(lsqk);
                datademo.add(lsqk); //新增落实情况
                datademo.add(qtdw);
                dataList.add(datademo);
            }
            log.writeLog("end set data");
            log.writeLog(dataList.toString());
            if(dataList.size()>0){//设置 Word数据
                int w=(WordExport.DOCW-3000);
                int h=WordExport.DOCH;
                WordExport wordExport=new WordExport(w,h);
                //3700,3700  落实情况  牵头单位
                List<String> title11 = new ArrayList<String>();
                title11.add(bt);
                log.writeLog(wihcol);
                int[] colWidths=getCellW(wihcol,w,wihcol);
                log.writeLog(colWidths);
                wordExport.makeWordjH(title11,dataList, new ArrayList<String>(), "",colWidths,jhlx);
                document=wordExport.getDocument();
            }

        }catch(Exception e){

        }
        return document;
    }
    /*
        判断是否存在 特批件
     */
    public boolean getCheckTpJan(Map<String,Object> params, User user){
        String userid=Util.null2String(user.getUID()+"");
        if("".equals(userid)||"0".equals(userid)){
            return false;
        }
        String zbdw=DubUtil.getZbdwByModelRy(userid);
        String sql="";
        String sqlwhere="";
        RecordSet re=new RecordSet();
        String DBType=re.getDBType();
        if("sqlserver".equals(DBType)){
            sqlwhere=" 1=1 and b.hj='3' and  a.jcdctz=b.id and a.jcdcrw=c.id  and isnull(a.qszt,-1) in (0,-1) and ','+cast(a.qtdw as varchar(4000))+',' like '%,"+zbdw+",%'  ";
        }else{
            sqlwhere=" 1=1 and b.hj='3' and  a.jcdctz=b.id and a.jcdcrw=c.id and isnull(a.qszt,-1) in (0,-1) and  ','||to_char(substr(a.qtdw,1,1000))||',' like '%,"+zbdw+",%'  ";
        }
        sql="select 1 from uf_jcrwfk a,uf_jcdctz b,uf_jcdcrw c where "+sqlwhere;
        log.writeLog("getCheckTpJan---->"+sql);
        re.execute(sql);
        if(re.next()){
            return true;
        }else{
            return false;
        }


    }
    //查询  当前人员的特批接口
    public Map<String, Object> getTpTablelist(Map<String,Object> params, User user) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        if (null == user){
            apidatas.put("hasRight", false);
            return apidatas;
        }
        try {
            String userid=Util.null2String(user.getUID()+"");
            //获取人员对应的主办单位
            String zbdw=DubUtil.getZbdwByModelRy(userid);
            //返回消息结构体
            WeaResultMsg result = new WeaResultMsg(false);
            RecordSet re=new RecordSet();
            String DBType=re.getDBType();
            //log.writeLog("DBType"+DBType);
            String pageID = "17ecc14c-9d64-4a43-81a4-7b7c6f7928571111";
            String pageUid = pageID + "_" + user.getUID();
            String pageSize = PageIdConst.getPageSize(pageID, user.getUID());

            String sqlwhere ="";
            if("sqlserver".equals(DBType)){
                sqlwhere=" 1=1 and b.hj='3' and  a.jcdctz=b.id and a.jcdcrw=c.id  and isnull(a.qszt,-1) in (0,-1) and ','+cast(a.qtdw as varchar(4000))+',' like '%,"+zbdw+",%'  ";
            }else{
                sqlwhere=" 1=1 and b.hj='3' and  a.jcdctz=b.id and a.jcdcrw=c.id  and isnull(a.qszt,-1) in (0,-1) and  ','||to_char(substr(a.qtdw,1,1000))||',' like '%,"+zbdw+",%'  ";
            }

            log.writeLog(sqlwhere);

            WeaTable table = new WeaTable();
            table.setPageUID(pageUid);
            table.setPageID(pageID);
            table.setPagesize(pageSize);

            String fileds = " a.*,c.bh,c.lb,'uf_jcdcrw' tablename,'sxlb' lbfield ";
            table.setBackfields(fileds);

            table.setSqlform(" uf_jcrwfk a,uf_jcdctz b,uf_jcdcrw c");
            table.setSqlwhere(sqlwhere);
            table.setSqlorderby("id");
            table.setSqlprimarykey("id");
            table.setSqlisdistinct("false");

            table.getColumns().add(new WeaTableColumn("id").setDisplay(WeaBoolAttr.FALSE));   //设置为不显示
            table.getColumns().add(new WeaTableColumn("20%", "编号", "bh","bh"));
            table.getColumns().add(new WeaTableColumn("30%", "任务内容", "rwnr","rwnr"));
            table.getColumns().add(new WeaTableColumn("20%", "牵头单位", "tqtdw"," tqtdw","com.api.sw.duban.util.dubanTran.getSwDpartmentnameByid"));
            WeaTableColumn sxlb=new WeaTableColumn("20%", "事项类别", "lb","lb","com.api.sw.duban.util.dubanTran.getSelectnameByValue");
            sxlb.setOtherpara("column:tablename").setOtherpara2("column:lbfield");
            table.getColumns().add(sxlb);
            table.getColumns().add(new WeaTableColumn("20%", "交办时间", "jbsj","jbsj"));
            //table.getColumns().add(new WeaTableColumn("10%", "操作", "opter","opter"));


            //增加右侧操作选项
            WeaTableOperates weaTableOperates = new WeaTableOperates();
            List<WeaTableOperate> operateList = new ArrayList<>();

            WeaTableOperate query = new WeaTableOperate("签收","","0");
            WeaTableOperate qs = new WeaTableOperate("签收","","1");

            //operateList.add(query);
            //operateList.add(qs);

            //设置check是否可用
            List<WeaTableCheckboxpopedom> checkboxpopedomList = new ArrayList<>();
            WeaTableCheckboxpopedom checkboxpopedom = new WeaTableCheckboxpopedom();
            checkboxpopedom.setPopedompara("column:id");
            checkboxpopedomList.add(checkboxpopedom);

            table.setCheckboxList(checkboxpopedomList);
            //table.setOperates(weaTableOperates);
            //weaTableOperates.setOperate(operateList);


            result.putAll(table.makeDataResult());
            result.put("hasRight", true);
            result.success();
            apidatas = result.getResultMap();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return apidatas;
    }
    public Map<String, Object> getCondition(Map<String,Object> params, User user) {

        Map<String, Object> apidatas = new HashMap<String, Object>();
        //角色判断参考代码
//        if(!HrmUserVarify.checkUserRight("LogView:View", user)){
//            apidatas.put("hasRight", false);
//            return apidatas;
//        }

        if (null == user){
            apidatas.put("hasRight", false);
            return apidatas;
        }

        apidatas.put("hasRight", true);

        /**
         * 高级搜索条件
         */
        ConditionFactory conditionFactory = new ConditionFactory(user);

        //条件组
        List<SearchConditionGroup> addGroups = new ArrayList<SearchConditionGroup>();

        List<SearchConditionItem> conditionItems = new ArrayList<SearchConditionItem>();

        //文本输入框
        SearchConditionItem wh = conditionFactory.createCondition(ConditionType.INPUT,502327, "wh");
        wh.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        wh.setFieldcol(16);	//条件输入框所占宽度，默认值18
        wh.setLabelcol(8);
        wh.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        wh.setLabel("文号"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(wh);


        //文本输入框
        SearchConditionItem bh = conditionFactory.createCondition(ConditionType.INPUT,502327, "bh");
        bh.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        bh.setFieldcol(16);	//条件输入框所占宽度，默认值18
        bh.setLabelcol(8);
        bh.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        bh.setLabel("编号"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(bh);

        //文本输入框
        SearchConditionItem bt = conditionFactory.createCondition(ConditionType.INPUT,502327, "bt");
        bt.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        bt.setFieldcol(16);	//条件输入框所占宽度，默认值18
        bt.setLabelcol(8);
        bt.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        bt.setLabel("标题"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(bt);

        addGroups.add(new SearchConditionGroup("查询条件",true,conditionItems));


        apidatas.put("condition",addGroups);

        return apidatas;

    }
    public JSONObject checkButton(Map<String,Object> params, User user){
        JSONObject json=new JSONObject();
        boolean flag=false;
        String rwid=Util.null2String(params.get("rwid")).trim() ;
        if(user==null||"".equals(Util.null2String(user.getUID()))||"".equals(rwid)){
            flag=false;
        }
        RecordSet re=new RecordSet();
        String DBType=re.getDBType();
        //log.writeLog("DBType"+DBType);

        String sql="select 1 from uf_dcsxzb where id='"+rwid+"' and  ISNULL(zt,-1) in (0,-1) and modedatacreater= "+user.getUID();
        re.execute(sql);
        if(re.next()){
            flag=true;
        }
        json.put("flag",flag);
        return json;
    }
    /*
        获取任务最新的反馈记录
     */
    public String getNewJlbyRwid(String rwid){
        String str="";
        RecordSet re=new RecordSet();
        String sql="select * from uf_jcdclsfkjl where fkrwid='"+rwid+"' and isnull(fkzt,-1) in (-1,0,1) order by modedatacreatedate,modedatacreatetime desc";
        re.execute(sql);
        if(re.next()){
            str=DocUtil.Html2Text(Util.null2String(re.getString("lsqk")) ) ;

        }
        return str;
    }
    /*
        通过递归获取数据  从下往上遍历
     */
    public void setListByRw(List<String> val,String rwid,int len){
        RecordSet re=new RecordSet();
        for(int i=len;i>0;i--){
            String sql="  select gzrw from (" +
                    " select gzrw,level from uf_jcdcrw start with id="+rwid+" " +
                    " connect by  prior sssj=domid ) where level= "+i;
            log.writeLog("setListByRw---"+sql);
            re.execute(sql);
            if(re.next()){
                val.add(re.getString("gzrw"));
            }else{
                val.add("");
            }
        }

    }
    //拼接列宽
    public int[] getCellW(int len,int Zw,int allcelllen){
        int[] cell=new int[allcelllen];
        int pz=Zw/(len);
        for(int i=0;i<len;i++){
            cell[i]=pz;
            log.writeLog(pz);
        }
        return cell;
    }
    /*
    获取任务最新的反馈记录
 */
    public String getNewFkbyRwid(String rwid){
        String str="";
        RecordSet re=new RecordSet();
        String sql="select * from uf_jcdclsfkjl where fkrwid='"+rwid+"' and isnull(fkzt,-1) in (-1,0,1) order by modedatacreatedate,modedatacreatetime desc";
        re.execute(sql);
        if(re.next()){
            str=DocUtil.Html2Text(Util.null2String(re.getString("lsqk")) ) ;

        }
        return str;
    }
}
